$(function () {

  function initRenderBanner () {
    new Swiper('.dm-main-banner .swiper', {
      loop: true,
      lazyLoadingInPrevNextAmount: 1,   //加载下一个slide
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      pagination: {
        el: ".swiper-pagination",
        clickable: true,
      },

    });
  }


  function initRenderSolutions () {
    new Swiper('.solutions-swiper', {
      loop: true,
      slidesPerView: 3,   // 一行展示 3 个
      spaceBetween: 40,   // 每个 slide 之间的间距（可调，比如 20px）
      pagination: {
        el: ".swiper-pagination",
        clickable: true,
      },
      breakpoints: {
        0: { // 当屏幕宽度 >=0 时，覆盖配置（相当于小屏）
          slidesPerView: 1,
          spaceBetween: 10,
        },
        768: { // 当屏幕宽度 >=768px 时，覆盖配置
          slidesPerView: 3,
          spaceBetween: 20,
        }
      }
    });
  }

  // 定义映射关系
  const dropdownMap = {
    '#countryList': DropdownOptions.CountryListSelect || [],
    '#retailerList': DropdownOptions.RetailerOptions || [],
    '#diamondList': DropdownOptions.DiamondOptions || [],
    '#quantityList': DropdownOptions.QuantityOptions || []
  }
  // 渲染函数
  function renderOptions ($ul, options) {
    $ul.empty()
    options.forEach(opt => {
      $ul.append(`<li data-value="${opt.value}">${opt.label}</li>`)
    })
  }


  // 批量渲染
  Object.entries(dropdownMap).forEach(([selector, options]) => {
    renderOptions($(selector), options)
  })

  // 打开/关闭当前下拉（并关闭其它）
  $('.select-dropdown').on('click', function (e) {
    e.stopPropagation()
    $('.select-dropdown').not(this).removeClass('open')
    $(this).toggleClass('open')
  })
  $(document).on('click', () => $('.select-dropdown').removeClass('open'))
  $('.select-dropdown').click(function () {
    var dropdown = $(this)
    var ul = dropdown.children('ul')
    var p = dropdown.find('p')
    var input = dropdown.find('input')
    // 如果为二级下拉
    if (ul.find('ul li').length) {
      var li = ul.find('ul li')
    } else {
      // 一级
      var li = ul.find('li')
    }

    var arrows = dropdown.find('.select-arrows')
    if (ul.css('display') == 'none') {
      ul.slideDown('fast')
      arrows.css('transform', 'rotate(180deg)')
    } else {
      ul.slideUp('fast')
      arrows.css('transform', 'rotate(0)')
    }

    li.click(function () {
      var txt = $(this).text()
      var firstSelect = $(this).parent().prev().text()
      p.html(`${firstSelect} ${txt}`)
      input.val(`${firstSelect} ${txt}`)
      ul.slideUp('fast')
      arrows.css('transform', 'rotate(0)')
      // 如果选中的是 'Other'，则将 select-dropdown 的宽度设置为 50%
      if ($(this).parent().parent().hasClass('selfSelect')) {
        if (txt == 'Other') {
          dropdown.css('width', '50%')
          var itemsValue = $(this).parent().parent().parent().find('.abcd')
          itemsValue.css('width', '50%')
          // 展示 input
          dropdown.parent().find('.attribute_input').css('display', 'block')
        } else {
          dropdown.css('width', '100%')
          var itemsValue = $(this).parent().parent().parent().find('.abcd')
          itemsValue.css('width', '0')
          dropdown.parent().find('.attribute_input').css('display', 'none')
          dropdown.parent().find('.attribute_input').val('')
          dropdown.parent().find('.error-message').text('') // 移除错误信息
        }
      }
    })
    dropdown.mouseleave(function () {
      ul.slideUp('fast')
      arrows.css('transform', 'rotate(0)')
    })
  })

  // 点击其他地方关闭下拉
  $(document).click(function () {
    $('.select-dropdown').removeClass('open')
  })

  // 通用校验函数
  function validateField (rule, $context) {
    const $input = $context.find(`#${rule.key}`) // 只在 $context 内查找
    const $error = $input.closest('.form-item').find('.error-message')
    // 根据类型获取值
    let value
    if ($input.attr('type') === 'checkbox') {
      value = $input.prop('checked') // true 或 false
    } else {
      value = $input.val().trim()
    }

    // 必填校验
    if (rule.required && !value) {
      $error.text(rule.errorMessage.required).addClass('show')
      return false
    }
    // 最大长度校验
    if (rule?.maxLength && value.length > rule.maxLength) {
      $error.text(rule.errorMessage.maxLength).addClass('show')
      return false
    }

    // 正则校验
    if (rule?.regex && value && !rule?.regex.test(value)) {
      $error.text(rule.errorMessage.regex).addClass('show')
      return false
    }

    // 校验通过
    $error.removeClass('show')
    return true
  }

  // 校验字段
  const validationRules = [
    {
      key: 'nameQuote',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter your name',
        maxLength: 'The length cannot exceed 50'
      }
    },
    {
      key: 'companyName',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter companyName',
      }
    },
    {
      key: 'diamondData',
      required: true,
      errorMessage: {
        required: 'Please select Diamond',
      }
    },
    {
      key: 'footerQuantity',
      required: true,
      errorMessage: {
        required: 'Please select quantity',
      }
    },
    {
      key: 'checkbox',
      required: false
    },
    {
      key: 'email',
      required: true,
      maxLength: 30,
      regex: regEmail,
      errorMessage: {
        required: 'Please enter your email',
        maxLength: 'The length cannot exceed 30',
        regex: 'Please enter a valid email'
      }
    },
    {
      key: 'country',
      required: true,
      errorMessage: {
        required: 'Please Select your Country'
      }
    },
    {
      key: 'retailer',
      required: true,
      errorMessage: {
        required: 'Please Select your Retailer'
      }
    },
    {
      key: 'phone',
      required: true,
      regex: regPhone,
      errorMessage: {
        required: 'Please enter your Phone',
        regex: 'Please enter a valid phone number'
      }
    }
  ]

  function getFormValues (leaveRulesData, $context) {
    let allValid = true
    const formValues = {}

    leaveRulesData.forEach(rule => {
      // 匹配 input / textarea / select
      const $el = $context.find(
        "input[name='" +
        rule.key +
        "'], textarea[name='" +
        rule.key +
        "'], select[name='" +
        rule.key +
        "']"
      )

      let value = ''

      if ($el.length) {
        const tag = $el.prop('tagName').toLowerCase()
        const type = ($el.attr('type') || '').toLowerCase()

        if (tag === 'input') {
          if (type === 'checkbox') {
            // 多选框 -> 取所有勾选的值
            value = $context
              .find("input[name='" + rule.key + "']:checked")
              .map(function () {
                return $(this).val()
              })
              .get()
          } else if (type === 'radio') {
            // 单选框 -> 取被选中的值
            value =
              $context.find("input[name='" + rule.key + "']:checked").val() ||
              ''
          } else {
            // 普通 input
            value = ($el.val() || '').trim()
          }
        } else if (tag === 'textarea') {
          value = ($el.val() || '').trim()
        } else if (tag === 'select') {
          value = $el.val()
        }
      }

      formValues[rule.key] = value

      // 校验必填或有校验规则的字段
      if (rule.required || rule.regex) {
        if (!validateField(rule, $context)) {
          allValid = false
        }
      }
    })

    return allValid ? formValues : null
  }

  // 根据文件名获取 SVG
  function getFileIcon (filename) {
    const ext = filename.split('.').pop().toLowerCase()
    for (let item of ENUM_FILE_TYPE) {
      if (Array.isArray(item.label)) {
        if (item.label.includes(ext)) return item.svgIcon
      } else if (item.label === ext) {
        return item.svgIcon
      }
    }
    // 默认图标
    return `./img/PC/doc_pc.png`
  }


  const $fileInput = $('#uploadInput')
  const $uploadBtn = $('#handleUploadFile')
  const $fileContent = $('.file-content')
  let uploadedFiles = [] // 存储已上传的文件
  // 点击按钮触发文件选择
  $uploadBtn.on('click', function () {
    $fileInput.click()
  })

  // 文件选择后处理
  $fileInput.on('change', function (e) {
    const files = e.target.files
    if (!files || files.length === 0) return
    // 将文件添加到缓存数组
    uploadedFiles = uploadedFiles.concat(Array.from(files))

    // 遍历文件
    Array.from(files).forEach(file => {
      // 上传成功后显示到页面（模拟）
      const svgIcon = getFileIcon(file.name)
      const formData = new FormData()
      formData.append('file', file)

      // 模拟上传，可替换成你的接口
      // 这里用 setTimeout 模拟异步上传
      setTimeout(() => {
        // 上传成功后显示到页面
        const fileHtml = `
      <div class="file-info">
        <div class="file-left-txt">
            <img src="${svgIcon}" alt="">
          <div class="file-name">${file.name}</div>
        </div>
        <img style="width:2rem;height:2rem;" src="../../img/PC/scusser_pc.png" alt="">
      </div>
    `
        $fileContent.append(fileHtml)
      }, 500)
    })

    // 重置 input，防止选择同一个文件不触发 change
    $fileInput.val('')
  })

  // 提交
  $('#handleSendBtn').click(function () {
    const $wrapper = $('.footer-form-content-product-sum')
    const formValues = getFormValues(validationRules, $wrapper)
    if (!formValues) return
    console.log(uploadedFiles)
  })
  initRenderSolutions()
  initRenderBanner()
});
